<?php
declare (strict_types = 1);

namespace app\patient\controller;

use think\facade\Db;

class Login{
    /**
     * @Notes: 患者端小程序登录
     * @Interface login
     * @author: Shaco
     * @Time: 2022/8/24-22:54
     */
    public function wxAppLogin(){
        $code = input('code');

        if(!$code || $code == 'undefined') return rejson(0, '参数错误');

        $headimg = '/image/headimg.png';  // 微信头像

        $APP_ID = 'wx8609f1192a7311cf';
        $APP_SECRET = '682ab4d52997ae60c137db789330d3c7';
        $GRANT_TYPE = 'authorization_code';
        $WX_LOGIN_URL = 'https://api.weixin.qq.com/sns/jscode2session';

        $params = [
            'appid'      => $APP_ID,
            'secret'     => $APP_SECRET,
            'js_code'    => $code,
            'grant_type' => $GRANT_TYPE,
        ];

        // 拼接请求地址
        $url = $WX_LOGIN_URL . '?' . http_build_query($params);
        $result = file_get_contents($url);
        $result = json_decode($result, true);

        if(array_key_exists('openid', $result)){
            $user = Db::name('user')->where(['wx_app_openid'=>$result['openid'],'isdel' => 0])->find();
            if($user){
                // 登陆
                return rejson(200,'登陆成功',['token' => login_token($user['id']),'user' => $user]);
            }else{
                // 注册
                $num = Db::name('user')->insertGetId(['headimg' => $headimg,'wx_app_openid' => $result['openid']]);
                if($num){
                    $user = Db::name('user')->where(['id'=>$num,'isdel' => 0])->find();
                    return rejson(200,'登陆成功',['token' => login_token($user['id']),'user' => $user]);
                }else{
                    return rejson(0,'登陆失败');
                }
            }
        }else{
            return rejson(0,'登陆失败');
        }
    }
}